import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt(); // 点的数量
        int m = scanner.nextInt(); // 边的数量
        int[][] edges = new int[m][2]; // 存储边的信息
        int[] dist = new int[n + 1]; // 存储从1号点到每个点的最短距离

        // 初始化dist数组为无穷大
        Arrays.fill(dist, Integer.MAX_VALUE);

        // 读取边的信息
        for (int i = 0; i < m; i++) {
            edges[i][0] = scanner.nextInt();
            edges[i][1] = scanner.nextInt();
        }

        // 创建图的邻接表表示
        List<List<Integer>> graph = new ArrayList<>();
        for (int i = 0; i <= n; i++) {
            graph.add(new ArrayList<>());
        }
        for (int i = 0; i < m; i++) {
            int u = edges[i][0];
            int v = edges[i][1];
            graph.get(u).add(v);
            graph.get(v).add(u); // 无向图，需要添加两次
        }

        // 执行BFS
        bfs(graph, dist, 1, n);

        // 输出结果
        if (dist[n] == Integer.MAX_VALUE) {
            System.out.println(-1);
        } else {
            System.out.println(dist[n]);
        }
    }

    public static void bfs(List<List<Integer>> graph, int[] dist, int start, int end) {
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(start);
        dist[start] = 0; // 起点到自己的距离是0

        while (!queue.isEmpty()) {
            int u = queue.poll();

            for (int v : graph.get(u)) {
                if (dist[v] == Integer.MAX_VALUE) { // 如果v未被访问
                    dist[v] = dist[u] + 1;
                    queue.offer(v);
                }
            }
        }
    }
}
